from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from django_filters import rest_framework as filters
from company.models import VehicleCompanyTerminal, Vehicle
from media.models import Media, VideoStream
from media.serializers import MediaSerializer, VideoStreamSerializer, MediaListSerializer

from .player import Player

player = Player()


class VideoStreamViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    queryset = VideoStream.objects.all()
    serializer_class = VideoStreamSerializer

    def create(self, request, *args, **kwargs):
        # 调用live视频(查询出imei,device_type)
        vehicle_id = request.data.get('vehicle_id')
        channel_id = request.data.get('channel_id')

        vct = VehicleCompanyTerminal.objects.filter(vehicle_id=vehicle_id).first()
        terminal = vct.terminal
        device_type = terminal.device_type

        video_stream = VideoStream.objects.filter(channel_id=channel_id, terminal=terminal).first()
        # if video_stream:
        #     return Response({'resp_code': 1, 'message': video_stream.uri, 'id': video_stream.id})

        uri_msg = player.start(vehicle_id, channel_id, device_type, terminal, vct)
        uri = uri_msg['message']
        if uri:
            serializer = self.get_serializer(
                data={'terminal': terminal.id, 'channel_id': request.data['channel_id'], 'uri': uri})
            serializer.is_valid(raise_exception=True)
            video_stream = serializer.save()
            return Response({'resp_code': 1, 'message': uri, 'id': video_stream.id})
        return Response({'resp_code': 0, 'message': None, 'id': None})


class MediaFilter(filters.FilterSet):
    start_time = filters.DateTimeFilter(field_name='start_time', lookup_expr='gte')
    license_number = filters.CharFilter(method='filterset_license_number')
    video_type = filters.CharFilter(method='filterset_video_type')

    def filterset_license_number(self, queryset, name, value):
        if value == "":
            return queryset
        terminal_ids = VehicleCompanyTerminal.objects.filter(vehicle__license_number=value).values_list('terminal_id', flat=True)
        return queryset.filter(terminal_id__in=terminal_ids)

    def filterset_video_type(self, queryset, name, value):
        if value == "":
            return queryset
        elif value == "A":
            return queryset.filter(uri__startswith='A')
        else:
            return queryset.filter(uri__startswith='B')

    class Meta:
        model = Media
        fields = ('start_time', 'license_number', 'video_type')


class MediaViewSet(ModelViewSet):
    """
    需要过滤出当前公司下的车辆回放视频
    """
    queryset = Media.objects.all()
    serializer_class = MediaSerializer
    filterset_class = MediaFilter
    filterset_fields = ('start_time', 'license_number', 'video_type')
    pagination_class = None

    def get_serializer_class(self):
        if self.action == 'list':
            return MediaListSerializer
        return self.serializer_class

    def get_queryset(self):
        if self.action == "list":
            company = self.request.user.company
            terminal_ids = VehicleCompanyTerminal.objects.filter(company=company).values_list('terminal_id', flat=True)
            return Media.objects.filter(terminal_id__in=terminal_ids)
        return self.queryset
